// lib/animation_feedback.dart
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:audioplayers/audioplayers.dart';

// 数字积木组件
class NumberBlock extends StatelessWidget {
  final String text;
  final Color backgroundColor;

  const NumberBlock({
    Key? key,
    required this.text,
    this.backgroundColor = Colors.yellowAccent,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 60,
      height: 60,
      decoration: BoxDecoration(
        color: backgroundColor,
        border: Border.all(color: Colors.deepOrange),
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 1,
            blurRadius: 2,
            offset: Offset(2, 2),
          ),
        ],
      ),
      child: Center(
        child: Text(
          text,
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

// 动画反馈类
class AnimationFeedback {
  AnimationFeedback(this.context);

  final BuildContext context;
  final AudioPlayer _audioPlayer = AudioPlayer();

  // 播放音频反馈
  Future<void> _playSound(bool isCorrect) async {
    print("_playSound");
    final asset = isCorrect
        ? AssetSource('audio/taibang.mp3')
        : AssetSource('audio/oo.mp3');
    await _audioPlayer.play(asset);
  }

  // 销毁音频播放器
  Future<void> dispose() async {
    print("dispose");
    await _audioPlayer.dispose();
  }

  // 显示凑十法动画反馈
  void startMakeTenAnimation({
    required int num1,
    required int num2,
    required int correctAnswer,
  }) {
    print('💡 开始凑十法动画，参数：num1=$num1, num2=$num2, correctAnswer=$correctAnswer');

    if (num1 + num2 >= 10 && (num1 > 5 || num2 > 5)) {
      final int makeTenStep = num1 > num2 ? (10 - num2) : (10 - num1);
      final int remaining =
          num1 > num2 ? (num1 - makeTenStep) : (num2 - makeTenStep);

      print('🔢 凑十步骤分解：makeTenStep=$makeTenStep, 剩余=$remaining');

      _showTwoNumbersAnimation(num1, num2)
          .then((_) => Future.delayed(800.milliseconds))
          .then((_) {
            if (ModalRoute.of(context)?.isCurrent ?? false) {
              print('➡️ 进入凑十步骤动画');
              return _showMakeTenStepAnimation(num1, num2, makeTenStep);
            } else {
              print('⚠️ 上下文已失效，跳过凑十步骤动画');
              return Future<void>.value();
            }
          })
          .then((_) => Future.delayed(800.milliseconds))
          .then((_) {
            if (ModalRoute.of(context)?.isCurrent ?? false) {
              print('➡️ 进入剩余部分动画');
              return _showRemainingAnimation(
                  num1, num2, makeTenStep, remaining);
            } else {
              print('⚠️ 上下文已失效，跳过剩余部分动画');
              return Future<void>.value();
            }
          })
          .then((_) => Future.delayed(800.milliseconds))
          .then((_) {
            if (ModalRoute.of(context)?.isCurrent ?? false) {
              print('➡️ 进入最终结果展示');
              return _showFinalResult(correctAnswer);
            } else {
              print('⚠️ 上下文已失效，跳过最终结果展示');
              return Future<void>.value();
            }
          });
    } else {
      print('⚠️ 不适合凑十法，使用简单计算动画');
      _showSimpleCalculationAnimation(num1, num2, correctAnswer);
    }
  }

  // 显示两个初始数字的动画
  Future<void> _showTwoNumbersAnimation(int num1, int num2) async {
    print('🎨 显示两个数字动画：num1=$num1, num2=$num2');

    try {
      final context = this.context;

      final animationCompleter = Completer<void>();
      final key = UniqueKey();

      await showModalBottomSheet(
        context: context,
        isDismissible: false,
        enableDrag: false,
        builder: (context) => Container(
          padding: EdgeInsets.all(20),
          margin: EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.5),
                spreadRadius: 2,
                blurRadius: 5,
                offset: Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  NumberBlock(
                          text: '$num1',
                          backgroundColor: Colors.yellow.shade700)
                      .animate()
                      .scale(
                          begin: Offset(0.5, 0.5),
                          end: Offset(1.0, 1.0),
                          duration: 400.milliseconds),
                  SizedBox(width: 30),
                  Icon(Icons.add, size: 30, color: Colors.deepOrange)
                      .animate()
                      .fade(duration: 300.milliseconds)
                      .then(
                          delay: 300.milliseconds,
                          duration: 300.milliseconds,
                          curve: Curves.easeInOut),
                  SizedBox(width: 30),
                  NumberBlock(
                          text: '$num2',
                          backgroundColor: Colors.yellow.shade700)
                      .animate()
                      .scale(
                          begin: Offset(0.5, 0.5),
                          end: Offset(1.0, 1.0),
                          duration: 400.milliseconds),
                ],
              ),
              SizedBox(height: 20),
              Text(
                '让我们用凑十法来看看怎么计算$num1 + $num2',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  print('✅ 点击了“下一步”按钮');
                  if (!animationCompleter.isCompleted) {
                    print('✅ 点击了“下一步”按钮，已完成');
                    animationCompleter.complete();
                    Navigator.of(context).pop(); // 添加这行代码以关闭当前对话框
                  }
                },
                child: Text('下一步'),
              ),
            ],
          ),
        ),
        isScrollControlled: true,
      );

      print('✅ 两个数字动画完成');
      
      // 等待用户点击或自动继续
      await animationCompleter.future;
    } catch (e, stackTrace) {
      print('❌ 动画中断：$e');
      rethrow;
    }
  }

  // 显示凑十步骤动画
  Future<void> _showMakeTenStepAnimation(
      int num1, int num2, int makeTenStep) async {
    final String firstNumber = num1 > num2 ? '$num1' : '$num2';
    final String secondNumber = num1 > num2 ? '$num2' : '$num1';

    print(
        '🎨 显示凑十步骤动画：firstNumber=$firstNumber, secondNumber=$secondNumber, makeTenStep=$makeTenStep');

    await showModalBottomSheet(
      context: context,
      isDismissible: false,
      enableDrag: false,
      builder: (context) => Container(
        padding: EdgeInsets.all(20),
        margin: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 5,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                NumberBlock(
                    text: firstNumber, backgroundColor: Colors.yellow.shade700),
                SizedBox(width: 10),
                Icon(Icons.add, size: 30, color: Colors.deepOrange),
                SizedBox(width: 10),
                NumberBlock(
                    text: secondNumber,
                    backgroundColor: Colors.yellow.shade700),
              ],
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '$firstNumber 可以分成 ',
                  style: TextStyle(fontSize: 16),
                ),
                NumberBlock(
                    text: '$makeTenStep',
                    backgroundColor: Colors.green.shade300),
                Text(
                  ' 和 $firstNumber - $makeTenStep',
                  style: TextStyle(fontSize: 16),
                ),
                NumberBlock(
                  text: '${int.parse(firstNumber) - makeTenStep}',
                  backgroundColor: Colors.yellow.shade700,
                ),
              ],
            )
                .animate()
                .slideY(begin: 0.5, end: 0.0, duration: 500.milliseconds),
            SizedBox(height: 20),
            Text(
              '我们可以先让$secondNumber 和 $makeTenStep凑成10',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                print('✅ 点击了“下一步”按钮');
                Navigator.of(context).pop(); // 关闭当前对话框
              },
              child: Text('下一步'),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
    );

    print('✅ 凑十步骤动画完成');
  }

  // 显示剩余部分动画
  Future<void> _showRemainingAnimation(
      int num1, int num2, int makeTenStep, int remaining) async {
    final String firstNumber = num1 > num2 ? '$num1' : '$num2';

    print(
        '🎨 显示剩余部分动画：firstNumber=$firstNumber, makeTenStep=$makeTenStep, remaining=$remaining');

    await showModalBottomSheet(
      context: context,
      isDismissible: false,
      enableDrag: false,
      builder: (context) => Container(
        padding: EdgeInsets.all(20),
        margin: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 5,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                NumberBlock(text: '10', backgroundColor: Colors.green.shade300),
                SizedBox(width: 10),
                Icon(Icons.add, size: 30, color: Colors.deepOrange),
                SizedBox(width: 10),
                NumberBlock(
                  text: '${int.parse(firstNumber) - makeTenStep}',
                  backgroundColor: Colors.yellow.shade700,
                ),
              ],
            ).animate().scale(
                begin: Offset(0.5, 0.5),
                end: Offset(1.2, 1.2),
                duration: 500.milliseconds),
            SizedBox(height: 20),
            Text(
              '然后再把剩下的${int.parse(firstNumber) - makeTenStep}加上去，\n$num1 + $num2 就等于${10 + (int.parse(firstNumber) - makeTenStep)}',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                print('✅ 点击了“下一步”按钮');
                Navigator.of(context).pop(); // 关闭当前对话框
              },
              child: Text('下一步'),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
    );

    print('✅ 剩余部分动画完成');
  }

  // 显示最终结果
  Future<void> _showFinalResult(int result) async {
    print('🎉 显示最终结果：result=$result');
    await showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: EdgeInsets.all(20),
        margin: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 5,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                NumberBlock(
                        text: '$result', backgroundColor: Colors.green.shade200)
                    .animate()
                    .scale(
                        begin: Offset(0.5, 0.5),
                        end: Offset(1.5, 1.5),
                        duration: 600.milliseconds),
              ],
            ),
            SizedBox(height: 20),
            Text(
              '答案是 $result',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                print('✅ 点击了“完成”按钮');
                Navigator.of(context).pop(); // 关闭当前对话框
              },
              child: Text('完成'),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
    );

    // 播放正确音效
    print('✅ 最终结果动画完成');
    await _playSound(true);
  }

  // 显示简单计算动画
  Future<void> _showSimpleCalculationAnimation(
      int num1, int num2, int correctAnswer) async {
    print('🎨 显示简单计算动画：num1=$num1, num2=$num2, correctAnswer=$correctAnswer');

    await showModalBottomSheet(
      context: context,
      isDismissible: false,
      enableDrag: false,
      builder: (context) => Container(
        padding: EdgeInsets.all(20),
        margin: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 5,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                NumberBlock(
                        text: '$num1', backgroundColor: Colors.yellow.shade700)
                    .animate()
                    .scale(
                        begin: Offset(0.5, 0.5),
                        end: Offset(1.0, 1.0),
                        duration: 400.milliseconds),
                SizedBox(width: 30),
                Icon(Icons.add, size: 30, color: Colors.deepOrange)
                    .animate()
                    .fade(duration: 300.milliseconds)
                    .then(
                        delay: 300.milliseconds,
                        duration: 300.milliseconds,
                        curve: Curves.easeInOut),
                SizedBox(width: 30),
                NumberBlock(
                        text: '$num2', backgroundColor: Colors.yellow.shade700)
                    .animate()
                    .scale(
                        begin: Offset(0.5, 0.5),
                        end: Offset(1.0, 1.0),
                        duration: 400.milliseconds),
              ],
            ),
            SizedBox(height: 20),
            Text(
              '让我们来看看怎么计算$num1 + $num2',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 20),
            Text(
              '答案是 $correctAnswer',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                print('✅ 点击了“完成”按钮');
                Navigator.of(context).pop(); // 关闭当前对话框
              },
              child: Text('完成'),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
    );

    print('✅ 简单计算动画完成');

    // 显示最终结果
    await Future.delayed(1500.milliseconds);
    await _showFinalResult(correctAnswer);
  }
}
